﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Text;

namespace blackhouse.Web.FasterFiles {
	public class FasterFilesHandler : IHttpHandler, IReadOnlySessionState {

		#region Fields

		#endregion

		internal static bool isLoaded = false;

		#region IHttpHandler Members

		public bool IsReusable {
			get { return false; }
		}

		public void ProcessRequest(HttpContext context) {
			try {
				string fExt = context.Request.Url.Segments.Last();
				fExt = fExt.ReplaceEx(".axd", "");
				fExt = fExt.Substring(fExt.LastIndexOf('.'));

				if(fExt == ".css") {
					string client = string.Empty;
					client = context.Request.Url.Segments[1].ReplaceEx("/", "");
					context.Response.Clear();
					context.Response.ContentType = "text/css";
					context.Response.Charset = "utf-8";
					FasterFilesProvider provider = new FasterFilesProvider();
					provider.GetCssContent(client, context.Response);
				}
				if(fExt == ".js") {
					string client = string.Empty;
					client = context.Request.Url.Segments[1].ReplaceEx("/", "");
					context.Response.Clear();
					context.Response.Charset = "utf-8";
					context.Response.ContentType = "application/x-javascript";

					FasterFilesProvider provider = new FasterFilesProvider();
					provider.GetJsContent(client, context.Response);
				}
				if(fExt == ".gif" || fExt == ".jpg" || fExt == ".png") {
					context.Response.Clear();
					context.Response.ContentType = "image/" + fExt;
#if RELEASE
                    context.Response.ExpiresAbsolute = DateTime.UtcNow.AddYears(1);
                    context.Response.Cache.SetLastModified(DateTime.UtcNow);
#endif
					context.Response.Cache.SetCacheability(HttpCacheability.Public);
					FasterFilesProvider provider = new FasterFilesProvider();
					provider.GetImgContent(context.Request.Url.Segments[1].Trim('/'), context.Request.Url.Segments[2].Trim('/'), fExt.Trim('.'), context.Response);
				}
			} catch(Exception e) {
				context.Response.Write(e);
			}
			//string hash = context.Request["cssid"];

			//if (!string.IsNullOrEmpty(hash))
			//{
			//    context.Response.Clear();
			//    context.Response.ContentType = "text/css";
			//    FasterFilesProvider.GetCssContent(hash, context.Response.OutputStream);
			//    context.Response.End();
			//    return;
			//}
			//hash = context.Request["jsid"];
			//if (!string.IsNullOrEmpty(hash))
			//{
			//    context.Response.Clear();
			//    context.Response.ContentType = "text/javascript";
			//    FasterFilesProvider.GetJsContent(hash, context.Response.OutputStream);
			//}
		}

		#endregion
	}
}